package com.qidian.tcba.admin.service.impl;


import com.qidian.tcba.admin.model.dto.district.DistrictListDTO;
import com.qidian.tcba.admin.model.entity.District;
import com.qidian.tcba.admin.service.DistrictService;
import com.qidian.tcba.dao.DistrictMapper;
import com.qidian.tcba.utils.BeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 区县表 服务实现类
 * </p>
 *
 * @author 冯永龙
 * @since 2021-07-06
 */
@Service
public class DistrictServiceImpl implements DistrictService {
    private static Map<Integer, List<DistrictListDTO>> districtCache = null;
    private final DistrictMapper districtMapper;

    public DistrictServiceImpl(DistrictMapper districtMapper) {
        this.districtMapper = districtMapper;
    }

    @Override
    public Map<Integer, List<DistrictListDTO>> getDistrictList() {
        return getDistrictCache();
    }

    /**
     * 第一次请求将所有区县存入缓存中，后续请求直接从缓存取即可
     * @return
     */
    private Map<Integer, List<DistrictListDTO>> getDistrictCache() {
        if (districtCache == null) {
            List<District> parentArea = districtMapper.findByParentId(1);
            districtCache = new HashMap<>();
            districtCache.put(1, BeanMapper.mapList(parentArea, DistrictListDTO.class));
            List<DistrictListDTO> list = districtCache.get(1);
            for (DistrictListDTO districtListDTO : list) {
                List<District> sonArea = districtMapper.findByParentId(districtListDTO.getId());
                districtListDTO.setSonArea(BeanMapper.mapList(sonArea, DistrictListDTO.class));
            }
        }
        return districtCache;
    }
}

